<?php

namespace app\api\service;

use app\api\model\AccountType;
use app\api\model\UserModel;
use think\Db;
use app\api\model\CustomerReconciliation as Reconciliation;

class CustomerReconciliation
{
    use SetAccountFlow;
    use GetFlowSum;

    /**
     *  客户对账单收款
     * @param $data
     * @return mixed
     */
    public static function receipt($data)
    {
        return Db::transaction(function () use ($data) {
            $res = [];
            $res[] = Reconciliation::create($data);
            $data['customer_type'] = 'user';
            $res[] = self::newReconciliationFlow($data);
            if (isset($data['discounted_price']) && !empty($data['discounted_price'])) {
                $res[] = self::newDiscountedPrice($data);
            }
            $res[] = self::updateCustomerArrears($data);
            if (empty(array_filter($res))) {
                return false;
            } else {
                return true;
            }
        });
    }

    /**
     * 期初调整
     * @param $data
     * @return mixed
     */
    public static function adjustment($data)
    {
        return Db::transaction(function () use ($data) {
            $data['customer_type'] = 'user';
            $res[] = self::newAdjustment($data);
            $res[] = self::adjustmentCustomerArrears($data);
            if (empty(array_filter($res))) {
                return false;
            } else {
                return true;
            }
        });
    }

    /**
     * 快速收款
     * @param $data
     * @return mixed
     */
    public static function quick($data)
    {
        return Db::transaction(function () use ($data) {
            $data['customer_type'] = 'user';
            $res = [];
            $res[] = Reconciliation::create($data);
            $res[] = self::newQuick($data);
            if (empty(array_filter($res))) {
                return false;
            } else {
                return true;
            }
        });
    }

    /**
     * 快速收款流水
     * @param $data
     * @return bool
     */
    protected static function newQuick($data)
    {
        $flowData = $data;
        $flowData['business_type'] = '客户快速收款';
        $flowData['business_number'] = $data['number'];
        $flowData['in_amount'] = $data['amount'];
        return self::newFlow($flowData);
    }

    /**
     * 新增期初调整流水
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected static function newAdjustment($data)
    {
        $flowData = $data;
        $flowData['account_type_id'] = AccountType::where('name', '期初调整')->find()['id'];
        $flowData['business_type'] = '期初调整收款';
        $flowData['business_number'] = $data['number'];
        $flowData['in_amount'] = $data['amount'];
        return self::newFlow($flowData);
    }

    /**
     * 新增收款对账流水
     * @param $data
     * @return bool
     */
    protected static function newReconciliationFlow($data)
    {
        $flowData = $data;
        $flowData['business_type'] = '客户对账单收款';
        $flowData['business_number'] = $data['number'];
        $flowData['in_amount'] = $data['amount'];
        return self::newFlow($flowData);
    }

    /**
     * 新增优惠对账流水
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected static function newDiscountedPrice($data)
    {
        $flowData = $data;
        $flowData['account_type_id'] = AccountType::where('name', '优惠金额')->find()['id'];
        $flowData['business_type'] = '优惠金额收款';
        $flowData['business_number'] = $data['number'];
        $flowData['in_amount'] = $data['discounted_price'];
        return self::newFlow($flowData);
    }

    /**
     * 更新客户欠款数
     * @param $data
     * @return mixed
     */
    protected static function updateCustomerArrears($data)
    {
        $customer = UserModel::find($data['customer_id']);
        $arrears = $customer['arrears'] - $data['amount'];
        if (isset($data['discounted_price'])) {
            $arrears = (float)$arrears - (float)$data['discounted_price'];
        }
        return $customer->save(['arrears' => $arrears]);
    }

    /**
     * 调整客户欠款数
     * @param $data
     * @return mixed
     */
    protected static function adjustmentCustomerArrears($data)
    {
        $customer = UserModel::find($data['customer_id']);
        $beginning = $data['amount'];
        $oldBeginning = $customer['beginning'];
        $oldAmount = $customer['arrears'];
        if ($oldBeginning) {
            //  更新时 余额为 原金额-原期初金额+期初金额
            $amount = ($oldAmount - $oldBeginning) + $beginning;
            return $customer->save(['arrears' => $amount, 'beginning' => $beginning]);
        } else {
            // 新增时 余额为 原金额+期初金额
            $amount = $oldAmount + $beginning;
            return $customer->save(['arrears' => $amount, 'beginning' => $beginning]);
        }
//        return $customer->save(['arrears' => $arrears]);
    }

    /**
     * 获取应付金额
     * @param $data
     * @return bool|mixed
     */
    public static function getTotal($data)
    {
        if ($data->customerReconciliation) {
            return $data->customerReconciliation['amount'];
        }
        if ($data->saleReturn) {
            return $data->saleReturn['payment'];
        }
        if ($data->sale) {
            return $data->sale['total'];
        }
        return 0;
    }

    /**
     * 获取实付金额
     */
    public static function getPayment($data)
    {
        if ($data->customerReconciliation) {
            return $data->customerReconciliation['amount'];
        }
        if ($data->saleReturn) {
            return $data->saleReturn['payment'];
        }
        if ($data->sale) {
            return $data->sale['payment'];
        }
        return 0;
    }
}
